#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@Author: kindey
@Date: 2025/8/7
@Description: 
"""
from rest_framework.views import APIView
from apps.serializers.data_serializer import (
    DataSerializer,
    DataCreateSerializer,
    DataDetailSerializer,
    DeviceWithRegionInfoSerializer
)
from apps.services.data_services import DataService, DictSmallClassService
from apps.utils.response_utils import rest_api_error,rest_api_success

class DataListView(APIView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.service = DataService()

    def get(self, request):
        data_list = self.service.get_all_data()
        serializer = DataSerializer(data_list, many=True)
        return rest_api_success(serializer.data)

    def post(self, request):
        serializer = DataCreateSerializer(data=request.data)
        if serializer.is_valid():
            data = self.service.create_data(serializer.validated_data)
            return rest_api_success(DataSerializer(data).data)
        return rest_api_error(serializer.errors)

class DataDetailView(APIView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.service = DataService()

    def get(self, request, data_id):
        data = self.service.get_data_by_id(data_id)
        if data:
            serializer = DataSerializer(data)
            return rest_api_success(serializer.data)
        return rest_api_success(msg="Data not found")

class DeviceDataView(APIView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.data_service = DataService()

    def get(self, request, device_id):
        # 对应SQL: select * from Data where device_id = 461 order by data_time
        data_list = self.data_service.get_data_by_device(device_id)
        serializer = DataSerializer(data_list, many=True)
        return rest_api_success(serializer.data)

class DeviceDataDetailView(APIView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.data_service = DataService()

    def get(self, request, device_id):
        # 对应复杂SQL查询: 获取设备数据及其详细信息
        data_list = self.data_service.get_device_data_with_details(device_id)
        serializer = DataDetailSerializer(data_list, many=True)
        return rest_api_success(serializer.data)

class DeviceRegionInfoView(APIView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.dict_service = DictSmallClassService()

    def get(self, request):
        # 对应SQL: 获取设备区域信息统计
        info_list = self.dict_service.get_devices_with_region_info()
        serializer = DeviceWithRegionInfoSerializer(info_list, many=True)
        return rest_api_success(serializer.data)
